package com.zxtc.wh.utils;

import java.sql.*;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * sql连接共享工具
 */
public class SqlUtil {
    private volatile static SqlUtil sql;

    // JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/file_database" + "?useUnicode=true&characterEncoding=UTF8";

    // 数据库的用户名与密码，需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "liushuhong";

    /*
    数据库
     */
    private Connection mConnection = null;
    //    WeakReference
    private WeakHashMap<SqlUtil, Map<String, ? extends Statement>> statementWeakHashMap = new WeakHashMap<>();

    /**
     * @return 获取一个实例
     */
    public static SqlUtil getInstance() {
        if (sql == null) {
            synchronized (SqlUtil.class) {
                if (sql == null) {
                    SqlUtil sqlUtil = new SqlUtil();
                    try {
                        sqlUtil.onBindDatebase();
                    } catch (ClassNotFoundException | SQLException e) {
                        e.printStackTrace();
                        return null;
                    }

                    return sql = sqlUtil;
                }
            }
        }
        return sql;
    }

    /**
     * 绑定初始化（连接）数据库
     */
    public void onBindDatebase() throws ClassNotFoundException, SQLException {
        // 注册 JDBC 驱动
        Class.forName(JDBC_DRIVER);

        // 打开链接
        System.out.println("连接数据库...");
        this.mConnection = DriverManager.getConnection(DB_URL, USER, PASS);
    }

    /**
     * 解绑（断开）数据库
     */
    public void onUnbindDatebase() {
        if (mConnection != null) {
            try {
                mConnection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param sqlCmd sql命令语句
     * @return 预编译的SQL数据库命令
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public PreparedStatement getStatement(String sqlCmd) throws SQLException, ClassNotFoundException {
        return mConnection.prepareStatement(sqlCmd);
    }


    /**
     * 获取返回最后的自增长的索引
     *
     * @param statement 发生在哪个sql命令中
     * @param type      自增长的索引的类型的类型
     * @param <T>       自增长的索引的类型
     * @return
     */
    public static <T> T getAutoIndex(Statement statement, Class<T> type) {
        ResultSet generatedKeys = null;
        try {
            generatedKeys = statement.getGeneratedKeys();
            if (generatedKeys.next()) {
                return generatedKeys.getObject(1, type);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}